<template>
  <a-modal :title="title" :width="800" v-model:visible="visible" @ok="onSubmit">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">
      <a-row>
        <a-col v-for="(i, idx) in appform" :key="idx + 'b'" :span="16">
          <a-form-item :label="i.label" :name="i.name">
            <a-input v-if="i.type === 'input' && i.name !== 'secret'" v-model:value="i.value" @change="valueChange" />
            <a-radio-group v-if="i.type === 'radio'" v-model:value="i.value" button-style="solid">
              <a-radio-button v-for="(e, num) in i.options" :value="e.value">{{ e.label }}</a-radio-button>
            </a-radio-group>
            <a-select v-if="i.type === 'select'" v-model:value="i.value" :mode="i.mode || ''" @change="valueChange" :options="i.options"></a-select>
            <a-textarea v-if="i.type === 'textarea'" v-model:value="i.value" :auto-size="{ minRows: 2, maxRows: 5 }" @change="valueChange" />
            <a-switch v-if="i.type === 'switch'" v-model:checked="i.value" :checkedValue="1" :unCheckedValue="0" @change="valueChange">
              <template #checkedChildren><check-outlined /></template>
              <template #unCheckedChildren><close-outlined /></template>
            </a-switch>
            <a-tree-select
              v-if="i.type == 'inputtree'"
              v-model:value="i.value"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择父级名称"
              allow-clear
              :fieldNames="{ title: 'title', key: 'key', value: 'key' }"
              tree-default-expand-all
              :tree-data="treeData"
              tree-node-filter-prop="title"
            >
              <template #title="{ value, title }">
                <span>{{ title }}</span>
              </template>
            </a-tree-select>
            <UploadImg v-if="i.type === 'img'" v-model:value="i.value"></UploadImg>
            <UploadFile v-if="i.type === 'upFile'" v-model:value="i.value" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, nextTick, reactive, toRaw, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import _ from 'lodash';
import UploadImg from '/@/components/file/img.vue';
import UploadFile from '/@/components/file/uploadFile.vue';
import { smartSentry } from '/@/lib/smart-sentry';
import { applicationManagementApi } from '/@/api/system/applicationManagement-api';
import { configureApi } from '../../../../api/system/configure-api.js';

// 基本信息form
const appform = ref([
  { label: '岗位编码', name: 'postCode', value: '', type: 'input', options: [], disabled: false },
  { label: '岗位名称', name: 'postName', value: '', type: 'input', options: [], disabled: false },
  { label: '部门编号', name: 'departmentId', value: '', type: 'input', options: [], disabled: false },
  { label: '部门名称', name: 'department', value: '', type: 'inputtree', options: [], disabled: false },
  { label: '排序', name: 'sortIndex', value: '', type: 'input', options: [], disabled: false },
  { label: '状态', name: 'status', value: '', type: 'switch', options: [], disabled: false },
]);

const treeData = ref([]);
const activeKey = ref(0);
// emit
const emit = defineEmits(['reload']);

// 组件ref
const formRef = ref();

const formDefault = {
  id: undefined,
};
let form = reactive({ ...formDefault });
const rules = {
  postCode: [{ required: true, message: '请输入', trigger: 'blur' }],
  postName: [{ required: true, message: '请输入', trigger: 'blur' }],
  sortIndex: [{ required: true, message: '请输入', trigger: 'blur' }],
};
// 是否展示抽屉
const visible = ref(false);
const formType = ref(null);
const title = ref('');

function showDrawer(rowData, index, type, queryForm) {
  Object.assign(form, formDefault);
  title.value = type;
  formType.value = index;
  if (index) {
    //添加
    if (queryForm) {
      onClose(queryForm);
    } else {
      onClose();
    }
  } else {
    //编辑
    appform.value.forEach((i) => {
      i.value = rowData[i.name] || '';
    });
    Object.assign(form, rowData);
  }
  appform.value.forEach((i) => {
    form[i.name] = i.value;
  });

  visible.value = true;
}

//添加之前清空
function onClose(a) {
  appform.value.forEach((i) => {
    i.value = i.defaultValue || '';
    if (i.name == 'status') {
      i.value = 1;
    } else if (i.name == 'sortIndex') {
      i.value = '1';
    }
    if (i.name == 'departmentId' && a) {
      i.value = a.departmentId;
    }
    if (i.name == 'department' && a) {
      i.value = a.departmentId;
    }
  });
  visible.value = false;
}

const paramObj = {};

function valueChange() {
  paramObj['switch_status'] = true;
  appform.value.forEach((i) => {
    if (i.name === 'select_authorizedGrantTypes' && i.value && i.value.length) {
      paramObj['authorizedGrantTypes'] = i.value.join(',');
    } else if (i.name === 'select_scope' && i.value && i.value.length) {
      paramObj['scope'] = i.value.join(',');
    } else {
      paramObj[i.name] = i.value;
    }
  });
  Object.assign(form, paramObj);
}

async function onSubmit() {
  valueChange();

  formRef.value
    .validate()
    .then(async () => {
      // SmartLoading.show();
      try {
        let res;
        //1 新增  0编辑
        if (formType.value == 1) {
          res = await configureApi.addPosts(paramObj);
        } else {
          res = await configureApi.adaptersUpdate(paramObj);
        }

        message.success(`${form.id ? '修改' : '添加'}成功`);
        onClose();
        emit('reload');
      } catch (error) {
        smartSentry.captureError(error);
      } finally {
        // SmartLoading.hide();
      }
    })
    .catch((error) => {
      console.log('error', error);
      message.error('参数验证错误，请仔细填写表单数据!');
    });
}

// 查询部门列表并构建 部门树
async function queryDepartmentTree() {
  let res = await configureApi.getOrgsTree();
  nextTick(() => {
    treeData.value = buildTree(res.data.nodes);
  });
}

function buildTree(data) {
  const tree = [];
  const map = {};
  // 先把所有节点放入一个映射表
  data.forEach((item) => {
    // map[item.key] = { ...item, children: [] };
    map[item.key] = { title: item.title, key: item.key, parentKey: item.parentKey, children: [] };
  });

  // 构建树
  data.forEach((item) => {
    const { parentKey } = item;
    if (parentKey === '0') {
      // 如果是根节点
      tree.push(map[item.key]);
    } else {
      // 如果有父节点，则将当前节点添加到父节点的 children 中
      if (map[parentKey]) {
        map[parentKey].children.push(map[item.key]);
      }
    }
  });
  return tree;
}
onMounted(() => {
  queryDepartmentTree();
});
defineExpose({
  showDrawer,
});
</script>
